Get premium membership and access questions with answers, video lessons as well as revision papers.

Given the following class declaration; class dynarray { int *p; int size; public: dynarray(int s); int &put(int i); int get(int i); //create operator=( function }; fill in all the details that will create a...

      

Given the following class declaration;
class dynarray {
int *p;
int size;
public:
dynarray(int s);
int &put(int i);
int get(int i);
//create operator=( function
};
fill in all the details that will create a dynamic array type. That is, allocate memory for the array, storing a pointer to this memory i p. Store the size of the array, in bytes, in size. Have put() return a reference to the specified element, and have get() return the value of a specified element. Dont allow the boundaries of the array to be overrun. Also, overload the assignment operator so that the allocated memory of each array is not accidentally destroyed when one array is assigned to another.

  

Answers


Davis

#include
#include
using namespace std;
class dynarray {
int *p;
it size;
public:
dynarray(int s);
int &put(int i);
int get(int i);
dynarray &operator=(dynarray &ob);
};
dynarray::dynarray(int s)
{
p = new int [
if(!p) {
cout << "Allocation error\n";
exit(1);
}
size = s;
}
int &dynarray::put(int i)
{
if(i=size) {
cout << "Bounds errorit(1);
}
return p[i];
}
int dynarray::get(int i)
{
if(i<0 || i>=size) {
cout << "Bounds error!\n";
exit();
}
return p[i];
}
for dynarray
dynarray &dynarray::operator =(dynarray &ob)
{
int i;
if(size!=ob.size) {
cout << "Cannot copy arrays of differing sizes!\n";
exit(1)
for(i = 0; ireturn *this;
}
int main()
{
int i;
dynarray ob1(10), ob(10), ob3(100);
ob1.put(3) = 10;
i = ob1.g
cout << i << "\n";
ob2 = ob1;
i = ob2.get(3);
cout << i << "\n";
// generates an error
ob = ob3; // !!!
return 0;
Githiari answered the question on June 8, 2018 at 18:50


Next: Using a friend, show how to overload the -- relave to the coord class. Define both the prefix and postfix forms.
Previous: Given the class below, class three_d{ int x, y, z; three_(int i, int j, int k) { x = i; y = j; z = k; } three_() {x=0; y=0;...

View More Computer Science Questions and Answers | Return to Questions Index


Learn High School English on YouTube

Related Questions